package site.xuxingcan.NettyUtil.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import site.xuxingcan.Model.RoomActionModel;
import site.xuxingcan.NettyUtil.DataUtil;

/**
 * Created by xuxingcan on 16-7-26.
 */
public class RoomActionHandler extends SimpleChannelInboundHandler<RoomActionModel> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RoomActionModel roomActionModel) throws Exception {
        if (DataUtil.isUserOk(roomActionModel.getUserName(), roomActionModel.getRandomString())) {
            switch (roomActionModel.getAction()) {
                case RoomActionModel.NEW_ROOM:
                    DataUtil.getNewRoom(roomActionModel);
                    break;
                case RoomActionModel.GET_IN_ROOM:
                    DataUtil.getInRoom(roomActionModel);
                    break;
                case RoomActionModel.OUT_OF_ROOM:
                    DataUtil.outOfRoom(roomActionModel);
                    break;
            }
        } else {
            //error
            roomActionModel.setResult(false);
        }
        channelHandlerContext.writeAndFlush(DataUtil.gson.toJson(roomActionModel));

        DataUtil.RoomModel roomModel = channelHandlerContext.channel().attr(DataUtil.NETTY_ROOM_KEY).get();
        if (roomModel != null) {
            roomModel.startGame();
        }
    }
}
